/*
ont-space - The ontology-based resource metadata repository
Copyright (c) 2006-2008, Information Eng. Research Unit - Univ. of Alcalá
http://www.cc.uah.es/ie
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along
with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package org.ontspace.util.translator.lom2owl.examples;

import com.hp.hpl.jena.rdf.model.ModelFactory;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.hp.hpl.jena.ontology.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.ieee.ltsc.lom.LOM;
import org.ieee.ltsc.lom.jaxb.lomxml.LOM_JAXBContext;
import org.ontspace.util.translator.lom2owl.adapter.vCardAdapter;

public class CreateLOM2OWLTranslator {

    static OntModel ontology;
    private static LOM lo;

    /**
     * This method calls LOM2OWLTranslatorImpl and it makes the translation
     * @param ontFileName the input ontology file
     * @param outFileName the output owl ontology file 
     * @param contentDirName the directory path that contains the input files
     * @param configFileName the xml file that contains lom values
     */
    public CreateLOM2OWLTranslator(String ontFileName, String outFileName,
            String contentDirName, String configFileName) {


        File ontFile, configFile, outFile, contentDir;
        try {

            ontFile =
                    new File(ontFileName);
            if (!ontFile.exists()) {
                System.out.println("ontology file not found");
                System.exit(-1);
            }

            outFile =
                    new File(outFileName);
            if (outFileName == null) {
                System.out.println("Output file not found");
                System.exit(-1);
            }

            configFile =
                    new File(configFileName);
            if (!configFile.exists()) {
                System.out.println("Config file not found");
            }

            contentDir =
                    new File(contentDirName);
            if (!contentDir.exists() && !contentDir.isDirectory()) {
                System.out.println("The folder with the xml files is not available.");
                System.exit(-1);
            }

            FileWriter errorFile =
                    new FileWriter("error.log");

            BufferedWriter bw =
                    new BufferedWriter(errorFile);
            PrintWriter errorWriter =
                    new PrintWriter(bw);
            errorWriter.println("WARNINGS");
            errorWriter.println("");


            InputStream ontStream =
                    new FileInputStream(ontFile);
            InputStream confStream =
                    new FileInputStream(configFile);
            OutputStream outStream =
                    new FileOutputStream(outFile);

            createOWLModel(ontStream);

            XMLFilter fileFilter =
                    new XMLFilter();
            String[] files =
                    contentDir.list(fileFilter);

            for (int i =
                    0; i < files.length; i++) {
                String fileName =
                        files[i];
                String lomXmlFilePath =
                        null;

                System.out.println("***************************************************************************");
                System.out.println("Initial XML File : " + contentDir + System.getProperty(
                        "file.separator") + fileName);

                try {
                    vCardAdapter vCard =
                            new vCardAdapter();
                    lomXmlFilePath =
                            vCard.adaptVCard(fileName, contentDirName);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //Elena: Se tiene que coger el adaptado porque si no se le pasa al parser el 
                //archivo con errores de formato

                //        lomXmlFilePath = contentDir + System.getProperty("file.separator") +
                //            fileName;

                System.out.println("Adapted XML File : " + lomXmlFilePath);
                InputStream lomStream =
                        new FileInputStream(lomXmlFilePath);

                lo =
                        parseLOMXML(lomStream);


//        LOMQueryManagerImpl qm = (LOMQueryManagerImpl) rep.getQueryManager("tipo");
//
//        MetadataRecordReference storeNewLearningObject =
//                        qm.storeNewLearningObject(lom,
//                        "http://www.cc.uah.es/ie/ont/lom2wsml#",
//                        "http://www.cc.uah.es/ie/ont/lom2wsml#lom2wsml-ont");
//
//
//                t.translate();
//
//                lomStream.close();
//                System.out.println("***************************************************************************");
//
            }

            ontology.write(outStream, "RDF/XML");

            ontStream.close();
            outStream.flush();
            outStream.close();
            errorWriter.flush();
            errorWriter.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**     
     * This main method
     * @param args They are a ontology initial, ontology final and metadata file     
     */
    public static void main(String[] args) throws IOException {
        String ontFile, outFile, contentDir, configFile;

        //it is possible to set up the parameters using the command line
        if (args.length < 4) {
            System.out.println(
                    "Four parameters must been set up to use the program: ontFile, outFile, " +
                    "contentDir and configFile.");
            System.out.println(
                    "Using the default values for the mandatory parameters.");
            ontFile =
                    new String(System.getProperty("user.dir") + System.getProperty(
                    "file.separator") + "lom2owl_etc" +
                    System.getProperty("file.separator") + "LOM2OWL.owl");
            Calendar cal =
                    Calendar.getInstance(new Locale("es"));
            SimpleDateFormat sdf =
                    new SimpleDateFormat("dd_MM_yyyy");
            outFile =
                    new String(System.getProperty("user.dir") + System.getProperty(
                    "file.separator") + "lom2owl_etc" +
                    System.getProperty("file.separator") + "output.owl");
            contentDir =
                    new String(System.getProperty("user.dir") +
                    System.getProperty("file.separator") + "lom2owl_etc" +
                    System.getProperty("file.separator") + "Metadatos");
            configFile =
                    new String(System.getProperty("user.dir") +
                    System.getProperty("file.separator") + "lom2owl_etc" +
                    System.getProperty("file.separator") + "config.xml");

        } else {

            System.out.println("Using the values obtained in the command line.");
            ontFile =
                    args[0];
            outFile =
                    args[1];
            contentDir =
                    args[2];
            configFile =
                    args[3];
        }
        System.out.println(" - ontFile: " + ontFile);
        System.out.println(" - outFile: " + outFile);
        System.out.println(" - contentDir: " + contentDir);
        System.out.println(" - configFile: " + configFile);

        CreateLOM2OWLTranslator tester =
                new CreateLOM2OWLTranslator(ontFile,
                outFile,
                contentDir, configFile);
    }

    /**
     * This method creates an Ontology Object that stores the ontoloy.
     */
    protected void createOWLModel(InputStream ontologyIS) throws IOException {
        if (ontology == null) {
            ontology =
                    ModelFactory.createOntologyModel();
            ontology.read(ontologyIS, "");
        }

    }

    public static void deleteDirectory(File path) {
        if (path.exists()) {
            File[] files =
                    path.listFiles();
            for (int i =
                    0;
                    i <
                    files.length;
                    i++) {
                if (files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                } else {
                    files[i].delete();
                }

            }
        }
        path.delete();
        return;

    }

    private class XMLFilter implements FilenameFilter {

        public boolean accept(File dir, String name) {
            return (name.endsWith(".xml"));
        }
    }

    /**
     * This method receives a LOM XML FILE and creates a LOM Object that 
     * stores its content. 
     * 
     */
    private final static LOM parseLOMXML(final InputStream is) throws JAXBException {

        final JAXBContext jaxbContext =
                JAXBContext.newInstance(System.getProperty(LOM_JAXBContext.CONTEXT_PATH_PROP,
                LOM_JAXBContext.DEFAULT_CONTEXT_PATH));

        final Unmarshaller unmarshaller =
                jaxbContext.createUnmarshaller();
        unmarshaller.setValidating(false);

        return (LOM) unmarshaller.unmarshal(is);

    }

    /**
     * This method parse in a LOM object from a LOM-XML file. 
     * 
     */
    protected static void createLOMFromInputStream(InputStream metadataIS)
            throws Exception {

        lo =
                parseLOMXML(metadataIS);

        System.out.println("");
        System.out.println("*************************************************" +
                "***************************");
        System.out.println("*  LOM XML FILE:                                 " +
                "                          *");
        System.out.println("*                                                " +
                "                          *");
        try {
            printLOMXML(lo, System.out);
        } catch (Throwable t) {
            t.printStackTrace();
            return;
        }

        System.out.println("*                                                " +
                "                          *");
        System.out.println("*************************************************" +
                "***************************");

    }
    //    
//    protected void createLOMfromInputStream(InputStream metadataIS)
//            throws Exception {
//
//        lom = parseLOMXML(metadataIS);
//
//
//    }
    private final static void printLOMXML(final LOM lom,
            final OutputStream outputStream) throws JAXBException {

        final JAXBContext jaxbContext =
                JAXBContext.newInstance(System.getProperty(LOM_JAXBContext.CONTEXT_PATH_PROP,
                LOM_JAXBContext.DEFAULT_CONTEXT_PATH));
        final Marshaller marshaller =
                jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(lom, outputStream);
        System.out.println();
        return;
    }
}

